package com.shujia.wyh;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.shujia.wyh.utils.MySqlTool;
import redis.clients.jedis.Jedis;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/*
    案例1：redis充当缓存存储验证码，设置过期时间，60s


 */

//TODO: 用户名密码未验证是否正确，正确后才可以输入手机号获取验证码  已解决！
//TODO: 手机号当作参数传入  已解决！

public class JedisDemo2 {
    public static void main(String[] args) throws Exception {
        init();

//        Scanner sc = new Scanner(System.in);
//        //查询所需的商品
//        System.out.println("请输入您要查询的商品"); //Apple MacBook Pro
//        String goods = sc.nextLine();
//
//        String info = findGoods(goods);
//        System.out.println(info);
    }

    public static void init() throws Exception{
        Scanner sc = new Scanner(System.in);

        System.out.println("=============||欢迎进入刘天保博彩中心 ^-^||==================");
        System.out.print("请输入用户名: ");
        String name = sc.next();
        System.out.print("请输入密码: ");
        String password = sc.next();

        int number = login(name,password); // 1. 未注册  2.登录失败  3. 登录成功
        switch (number){
            case 1:
                System.out.println("该用户不存在，请先注册！（Y/N）");
                String flag = sc.next();
                if("Y".equals(flag)){
                    System.out.println("******************************************");
                    System.out.print("请输入新用户的名称:");
                    String new_name = sc.next();
                    System.out.print("请输入新用户的密码:");
                    String new_password = sc.next();
                    System.out.print("请输入新用户的手机号:");
                    String new_phone = sc.next();

                    //获取当前的时间
                    String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()));

                    //获取数据库操作对象
                    Statement statement = MySqlTool.getStatement();
                    //执行插入功能
                    int i = statement.executeUpdate("insert into users(name,passwd,phone_num,create_time) values('" + new_name + "','" + new_password + "','" + new_phone + "','" + time + "')");
                    System.out.println("注册中，请稍后.....");
                    Thread.sleep(3000);
                    System.out.println((i==1)?"注册成功！！":"注册失败！！");
                }
                break;
            case 2:
                System.out.println("登录失败！！");
                break;
            case 3:
                System.out.println("登录成功！！！");

                //查询所需的商品
                System.out.println("请输入您要查询的商品"); //Apple MacBook Pro
                sc.nextLine();
                String goods = sc.nextLine();


                String info = findGoods(goods);
                System.out.println(info);

                break;
        }

    }

    /**
     *  加入了缓存查询数据的方法
     */
    public static String findGoods(String goods) throws Exception{

        String info = null;
        //先去redis中查询
        Jedis jedis = new Jedis("192.168.254.100", 7000);
        //将商品的名字当作key，商品的具体信息当作value值
        String s = jedis.get(goods); //Apple MacBook Pro【教育优惠】14英寸M2 Pro芯片(10核中央 16核图形)16G 512G 深空灰 笔记本MPHE3CH/A
        if(s==null){
            System.out.println("走的是mysql查询=======================");
            //就去mysql中查询
            PreparedStatement statement = MySqlTool.getStatement("select * from jd_goods where goods_name=?");
            System.out.println(goods);
            statement.setString(1,goods);

            ResultSet resultSet = statement.executeQuery();
            boolean next = resultSet.next();
            if(next){
                String goods_name = resultSet.getString(2);
                String goods_price = resultSet.getString(3);
                String goods_shop = resultSet.getString(4);
                String goods_comments = resultSet.getString(5);

                info = goods_name+"-"+goods_price+"-"+goods_shop+"-"+goods_comments;

                //将该数据添加到redis中
                jedis.set(goods,info);
            }
        }else {
            System.out.println("走的是Redis查询======================");
            info = s;
        }
        jedis.close();
        return info;

    }


    /**
     *  登录的方法
     */
    public static int login(String name,String password){
        Scanner sc = new Scanner(System.in);
        int num = 0;
        try {
            //向数据库中查询，判断用户是否存在
            String sql1 = "select * from users where name=?";

            //使用工具类获取预编译数据库操作对象
            PreparedStatement statement = MySqlTool.getStatement(sql1);
            statement.setString(1,name);
            //执行sql语句
            ResultSet resultSet = statement.executeQuery();

            boolean next = resultSet.next();
            if(!next){
                System.out.println("用户不存在，请先注册");
                num = 1;
            }else {
                //判断用户名和密码是否正确
                String sql2 = "select * from users where name=? and passwd=?";
                //获取数据库预编译对象
                PreparedStatement statement1 = MySqlTool.getStatement(sql2);
                statement1.setString(1,name);
                statement1.setString(2,password);
                //执行sql语句
                ResultSet resultSet1 = statement1.executeQuery();
                boolean next1 = resultSet1.next();

                if(!next1){
                    System.out.println("用户名密码不正确！！！");
                    num = 2;
                    return num;
                }


                System.out.print("请输入手机号: ");
                String phoneNumber = sc.next();
                sc.nextLine();
                while (true){
                    //生成验证码
                    String yzmCode = getYZMCode();

                    //调用阿里云短信服务发送验证码
                    String s = sendYZM(yzmCode,phoneNumber);
                    if("OK".equals(s)){
                        //将验证码存入到redis数据库中
                        saveYZMCode(yzmCode);
                        System.out.println("验证码已经发送，请在60秒内输入");
                        System.out.println("请输入验证码: ");
                        String yzm = sc.nextLine();

                        //从redis中获取验证码
                        Jedis jedis = new Jedis("192.168.254.100", 7000);

                        String s1 = jedis.get("yzm");
                        if(s1!=null){
                            if(yzm.equals(yzmCode)){
                                num = 3; //登录成功
                            }else {
                                num = 2; //登录失败
                            }
                            break;
                        }else {
                            System.out.println("验证码已经失效, 请重新获取！");
                            System.out.println("是否要重新获取(Y/N)");
                            String flag2 = sc.next();
                            if("Y".equals(flag2)){
                                continue;
                            }else {
                                break;
                            }
                        }
                    }
                }


            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return num;
    }

    /**
     *  将验证码存储到redis数据库中并设置过期时间
     */
    public static void saveYZMCode(String yzmCode){
        //获取与redis的连接
        Jedis jedis = new Jedis("192.168.254.100", 7000);

        jedis.setex("yzm",60,yzmCode);

        jedis.close();

    }



    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static String getYZMCode() {
        //使用StringBuilder拼接验证码
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append((int) (Math.random() * 10));
        }
        return sb.toString();
    }

    public static String sendYZM(String yzmCode,String phoneNum) throws Exception{
        String s = null;


        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        com.aliyun.dysmsapi20170525.Client client = createClient("xxxx", "xxxx");

        //生成验证码
//        String yzmCode = getYZMCode();

        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName("王友虎的博客")
                .setTemplateCode("SMS_462405826")
                .setPhoneNumbers(phoneNum)
                .setTemplateParam("{\"code\":\""+yzmCode+"\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            System.out.println(sendSmsResponse);
            s = sendSmsResponse.getBody().getMessage();
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return s;
    }


}
